<?php
/*
  Plugin Name: Adwit Banner Manager
  Plugin URI: http://www.adwit-server.com
  Description: Description
  Version: 0.0.1
  Author: Etineria Inc.
  Author URI: http://www.etineria.com
 */

/*  Copyright 2010  Etineria Inc  (email : info@adwitserver.com)

  This program is free software; you can redistribute it and/or modify
  it under the terms of the GNU General Public License, version 2, as
  published by the Free Software Foundation.

  This program is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  GNU General Public License for more details.

  You should have received a copy of the GNU General Public License
  along with this program; if not, write to the Free Software
  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 */
//error_reporting(E_ALL ^ E_WARNING ^ E_NOTICE);
define("ADWIT_BANNER_MANAGER_VERSION", "1.0.1");
define("ADWIT_HOME_URL", "http://www.adwit-express.com");
define('ADWIT_BANNER_MANAGER_PATH', WP_PLUGIN_DIR . '/adwit-banner-manager');
define("ADWIT_BANNER_IMAGES", '/wp-content/plugins/adwit-banner-manager/images');
load_plugin_textdomain('adwit', false, 'adwit-banner-manager/lang');

if (is_admin ()) {
  #    require_once('/home/dev1/webserver/php/wordpress/wp-content/plugins/logger.class.php');
    require_once(ADWIT_BANNER_MANAGER_PATH . '/adwit-banner-manager-admin.php');
}

function adwit_widget_options($reset=false) {
  global $widget_adwit_banner_data;
  if (empty($widget_adwit_banner_data) || $reset !== false) {
    $widget_adwit_banner_data = get_option('widget_adwit_banner');
  }
  return $widget_adwit_banner_data;
}

function adwit_options($reset=false) {
    global $adwit_data;
    if (empty($adwit_data) || $reset !== false) {
        $adwit_data = get_option('adwit_options');
    }
    return $adwit_data;
}

function adwit_option($option) {
    $options = adwit_options();
    return $options[$option];
}

add_action('admin_menu', 'adwit_dashboard');
add_action('admin_init', 'adwit_load_scriptaculus');

function adwit_dashboard() {
    add_object_page('adwit', 'Adwit-Banner', 'manage_options', 'adwit', 'adwit_banner_manage_ads');
    add_submenu_page('adwit', 'adwit > Manage', __('Manage Ads', 'adwit'), 'manage_options', 'adwit', 'adwit_banner_manage_ads');
    add_submenu_page('adwit', 'adwit > New Adwit Ads', __('New Adwit Ads', 'adwit'), 'manage_options', 'adwit_add', 'adwit_banner_add');
    add_submenu_page('adwit', 'adwit > Setup Adwit Ads', __('Setup Adwit Ads', 'adwit'), 'manage_options', 'adwit_setup', 'adwit_banner_setup');
}

function adwit_load_scriptaculus() {
    wp_enqueue_script('scriptaculous');
}

function adwit_banner_manage_ads() {

    if (adwit_find_or_create_customer ()) {
        adwit_banner_setup();
        exit();
    }

    $adwit_opt = adwit_options();
    if (empty($adwit_opt['adwit_express_key']) or empty($adwit_opt['adwit_express_publisher_id'])) {
        echo __('Empty key go to http://www.adwit-express.com', 'adwit');
        exit();
    } else {
        $data = array();
        $data['date'] = _get_date_now_adwit_format(); /* Tme.now format to 2010-12-09_20h50 */;
        $data['publisher_id'] = $adwit_opt['adwit_express_publisher_id'];

        echo "<iframe width='100%' height='600' src='" . ADWIT_HOME_URL . '/' . adwit_generate_token('campaign_ads/banners', $data, $adwit_opt['adwit_express_key']) . "'></iframe>";
    }
}

function adwit_banner_add() {
    if (adwit_find_or_create_customer ()) {
        adwit_banner_setup();
        exit();
    }

    echo "<iframe width='100%' height='600' src='" . ADWIT_HOME_URL . "'></iframe>";
}

function adwit_banner_setup() {
    //Fiind or create customer
    adwit_find_or_create_customer();

    //Check available Ads and set adwit_express_ads_enabled (true/false)
    adwit_check_ads();

    //$wg_opt_list = adwit_widget_options();
    //print_r($wg_opt_list);
    
    $options = adwit_options();
    $vp_type = 'page';
    
    if (isset($_POST['post_type']) && !empty($_POST['post_type'])){
        $vp_type = $_POST['post_type'];
    }

    switch ($vp_type) {
        case 'post':
            $view_page = 'post';
            $adwit_ads = _get_adwit_post_type_data($options['ads'], 'post');
            break;
        case 'home':
            $view_page = 'home';
            $adwit_ads = _get_adwit_post_type_data($options['ads'], 'home');
            break;
         case 'search':
            $view_page = 'search';
            $adwit_ads = _get_adwit_post_type_data($options['ads'], 'search');
            break;
        default:
            $view_page = 'page';
            $adwit_ads = _get_adwit_post_type_data($options['ads'], 'page');
            break;
    }

    include(ADWIT_BANNER_MANAGER_PATH . '/views/main.php');
}

function adwit_inject_hook($content) {
    if (is_home() || is_archive() || is_search() || is_page() || is_single() && !empty($content)) {

        $adwit_ads = _get_adwit_ads_data();
        if (empty($adwit_ads)) {
            return $content;
        }

        $paragraphes = preg_match_all("/(<p(.*?)<\/p>)/", $content, $result);

        if (count($result[0]) > 1) {
            $two_array = array_chunk($result[0], ceil(count($result[0]) / 2));

            $script_top = _get_adwit_ads('top');

            $two_array[0][0] = $script_top . $two_array[0][0];

            $script_middle = _get_adwit_ads('middle');
            $script_bottom = _get_adwit_ads('bottom');

            $two_array[1][2] = $two_array[1][2];

            $result = implode(array_merge($two_array[0], array($script_middle), $two_array[1]));

            $content = $result . $script_bottom;
        } else {
            $script_top = _get_adwit_ads('top');
            if (!empty($script_top)){
                 $content = $script_top.$content;
            }

            $script_bottom = _get_adwit_ads('bottom');
            if (!empty($script_bottom)){
                 $content = $content.$script_bottom;
            }
        }
    }

    return $content;
}

function adwit_title_inject_hook($content) {

    $script_head = '';
    $adwit_ads = _get_adwit_ads_data();

    if (empty($adwit_ads)) {
        return $content;
    }


    if ((is_home() || is_page())  && !empty($content) ) {
        $script_h = _get_adwit_ads('head');
        if (!empty($script_h)) {
            //$script_head = $script_h . '<div style="clear:left;">&nbsp;</div>';
        }
    }

    return $script_head . $content;
}

//add_filter('the_title', 'adwit_title_inject_hook');
add_filter('the_content', 'adwit_inject_hook');

function _get_adwit_post_type_data($ads, $type='page') {
    $res = array();
    if (is_array($ads) && !empty($ads)) {
        foreach ($ads as $key => $val) {
            if (0 == strcmp($type, substr($key, 0, strlen($type)))) {
                $res[$key] = $val;
            }
        }
    }
    return $res;
}

function _adwit_script_generator($key_id='', $w, $h) {

    if (empty($key_id)) {
        return;
    }

//    $key_id = '3770273667';
$ad = <<<SCRIPT
<script type="text/javascript" id="scawx-$key_id"><!--
adwitServer_client = "awx-$key_id";
adwitServer_client_width = $w;
adwitServer_client_height = $h;
adwitServer_output = 'div';
//-->
</script>
<script type="text/javascript" src="http://ads.adwitserver.com/script/show_ads.js"></script>
SCRIPT;

    return $ad;
}

function _get_adwit_ads_data() {
    $options = adwit_options();
    $res = array();
    if (is_page ()) {
        $res = _get_adwit_post_type_data($options['ads'], 'page');
    } elseif (is_single() || is_archive()) {
        $res = _get_adwit_post_type_data($options['ads'], 'post');
    } elseif (is_home()) {
        $res = _get_adwit_post_type_data($options['ads'], 'home');
    } elseif ( is_search()) {
        $res = _get_adwit_post_type_data($options['ads'], 'search');
    }
    return $res;
}

function _get_adwit_ads($pos='') {
    if (empty($pos)) {
        return '';
    }

    //echo 'aa',get_the_title(ID).'cc'; exit;
    $post_type = '';
    if (is_page ()) {
        $post_type = 'page_' . $pos;
    } elseif (is_single() || is_archive()) {
        $post_type = 'post_' . $pos;
    } elseif (is_home()) {
        $post_type = 'home_' . $pos;
    } elseif ( is_search()) {
        $post_type = 'search_' . $pos;
    }

    $adwit_ads = _get_adwit_ads_data();

    $script_pos = '';

    if ($adwit_ads[$post_type . '_left']) {
        $script_pos .= '<div style="float:left; margin-right: 5px;">' . _adwit_script_generator($adwit_ads[$post_type . '_left']['key'], $adwit_ads[$post_type . '_left']['width'], $adwit_ads[$post_type . '_left']['height']) . '</div>';
    }
    if ($adwit_ads[$post_type . '_right']) {
        $script_pos .= '<div style="float:right; margin-right: 5px;">' . _adwit_script_generator($adwit_ads[$post_type . '_right']['key'], $adwit_ads[$post_type . '_right']['width'], $adwit_ads[$post_type . '_right']['height']) . '</div>';
    }
    if ($adwit_ads[$post_type . '_center']) {
        $script_pos .= '<div style="width: 60px; margin: 0 auto;">' . _adwit_script_generator($adwit_ads[$post_type . '_center']['key'], $adwit_ads[$post_type . '_center']['width'], $adwit_ads[$post_type . '_center']['height']) . '</div>';
    }
    return $script_pos;
}



class Widget_Adwit_Banner extends WP_Widget {
    /** constructor */

    function Widget_Adwit_Banner() {
        require_once(ADWIT_BANNER_MANAGER_PATH . '/adwit-banner-manager-admin.php');
        adwit_find_or_create_customer();
    	$widget_ops = array('classname' => 'widget_adwit_banner', 'description' => __( 'Create and display your adwit-express ads', 'adwit') );
		parent::WP_Widget('adwit_banner', __('Adwit-Banner', 'adwit'), $widget_ops);
    }

    function widget($args, $instance) {

    	extract( $args );

		$sizeid = trim( $instance['sizeid'] );
                $key_id = trim( $instance['key'] );
                
		$title = apply_filters('widget_title', $instance['title']);
		if ( empty($title) ) $title = __( 'Adwit Banner', 'adwit' );

		echo "{$before_widget}{$before_title}" . esc_html($title) ."{$after_title}";

                if (!empty($key_id) && $sizeid > 0){

                     $bann_list = _get_bann_list();
                     //Add new banner info into adwit_options (wp)
                    $bsizes = array();

                    foreach($bann_list as $bk => $bv){
                        if ($bv['id'] == $sizeid){
                            $bsizes = explode('x', $bk);
                            break;
                        }
                    }
//                    $key_id = '3770273667';
                    echo '<div style="clear:left;">';
                   
$ad = <<<SCRIPT
<script type="text/javascript" id="scawx-$key_id"><!--
adwitServer_client = "awx-$key_id";
adwitServer_client_width = $bsizes[0];
adwitServer_client_height = $bsizes[1];
adwitServer_output = 'div';
//-->
</script>
<script type="text/javascript" src="http://ads.adwitserver.com/script/show_ads.js"></script>
SCRIPT;
                    echo $ad;
                    echo '</div>';
                }

	}


    /** @see WP_Widget::update */
    function update($new_instance, $old_instance) {
        $adwit_data = adwit_options();

        $instance['sizeid'] = trim( strip_tags( stripslashes( $new_instance['sizeid'] ) ) );
        $instance['title'] = trim( strip_tags( stripslashes( $new_instance['title'] ) ) );
        $tmp_sizeid = trim( strip_tags( stripslashes( $new_instance['tmp_sizeid'] ) ) );
        $wg_opt_list =  $this->_adwit_widget_filter($tmp_sizeid);

        $bann_list = _get_bann_list();

        $url_data = array();
        $url_data['page_type'] = 'widget';
        $url_data['pos_v'] = $new_instance['sizeid'];
        $url_data['pos_h'] = 0;
        $url_data['size_id'] = $new_instance['sizeid'];
        $url_data['status'] = 'on';
        $url_data['publisher_id'] = $adwit_data['adwit_express_publisher_id'];

        //Get zone key
        $url_express_create_zone = ADWIT_HOME_URL . '/' . adwit_generate_token('campaign_ads/zone_add', $url_data, $adwit_data['adwit_express_key']);
        $get_zone_key = wp_remote_fopen($url_express_create_zone);
        
        if ( !empty($tmp_sizeid) && $tmp_sizeid > 0 && $tmp_sizeid != $new_instance['sizeid']){
            $url_data['status'] = 'off';
            $url_data['pos_v'] = $tmp_sizeid;
            $url_data['size_id'] = $tmp_sizeid;
            $url_express_update_zone = ADWIT_HOME_URL . '/' . adwit_generate_token('campaign_ads/zone_add', $url_data, $adwit_data['adwit_express_key']);
            wp_remote_fopen($url_express_update_zone);
        }
  
        //Add new banner info into adwit_options (wp)
        $bsizes = array();
        $img_bsize = '';

        foreach($bann_list as $bk => $bv){
            if ($bv['id'] == $new_instance['sizeid']){
                $img_bsize = $bk;
                $bsizes = explode('x', $bk);
                break;
            }
        }

        $instance['page_type'] = 'widget';
        $instance['pos_v'] = $new_instance['sizeid'];
        $instance['pos_h'] = 0;
        $instance['width'] = $bsizes[0];
        $instance['height'] = $bsizes[1];
        $instance['bsize'] = $img_bsize;
        $instance['key'] = $get_zone_key; //zone key
        $instance['img_name'] = $img_bsize. '.png';
        
        return $instance;
    }

    function _adwit_widget_filter($tmp_sizeid = ''){
        $bann_list = _get_bann_list();
        /*
        $wg_opt_list = adwit_widget_options();

        if (!empty($tmp_sizeid)){
            foreach ($wg_opt_list as $kk => $vv){
                if ($tmp_sizeid == $vv['sizeid'] || empty($vv)){
                    unset($wg_opt_list[$kk]);
                }
            }
        }

        foreach ($bann_list as $k1 => $v1){
            foreach ($wg_opt_list as $v2){
                if ($v1['id'] == $v2['sizeid'] || empty($v1)){
                    //unset($bann_list[$k1]);
                }
            }
        }
        */
        return $bann_list;
    }
    /** @see WP_Widget::form */
    function form($instance){

        //widget_adwit_banner
		$instance = wp_parse_args( (array) $instance, array('sizeid' => '', 'title'=>'') );
		$sizeid = esc_attr($instance['sizeid']);

                $title = esc_attr($instance['title']);

                echo '<p>
      <label for="' . $this->get_field_id('title') . '">' . esc_html__('title:') . '
                            <input class="widefat" id="' . $this->get_field_id('title') . '" name="' . $this->get_field_name('title') . '" type="text" value="' . $title . '" />
                            </label>
                    </p>';

                $bann_list = $this->_adwit_widget_filter();

                echo '<p><select id="'.$this->get_field_id('sizeid').'" name="'.$this->get_field_name('sizeid').'">';
                    echo '<option value="">'.__('Select', 'adwit').'</option>';
                    foreach($bann_list as $key => $value){
                    echo '<option value="'.$value['id'].'" '.($sizeid==$value['id'] ? ' selected=true' : '').'>'.$key.'</option>';
                    }
                echo '</select> '.__('Add Banner', 'adwit').'
                    <input id="' . $this->get_field_id('tmp_sizeid') . '" name="' . $this->get_field_name('tmp_sizeid') . '" type="hidden" value="' . $sizeid . '" />
                    </p>';
               

    }

}

add_action( 'widgets_init', 'adwit_banner_init' );
function adwit_banner_init() {
	register_widget('Widget_Adwit_Banner');
}
?>